
package cn.xxl.cordova.install;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri; 
import java.io.File;
import android.os.Environment; 

public class InstallPlugin extends CordovaPlugin {

    public static final int INSTALL_CODE = 1;

    private CallbackContext callbackContext = null;

    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        
        this.callbackContext = null;

        if (action.equals("install")) {
            this.callbackContext = callbackContext;
            install(args);
            return true;
        }

        return false;
    }

    private void install (JSONArray args) throws JSONException {
        String url = Environment.getExternalStorageDirectory() + args.getString(0);

        final Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(url)), "application/vnd.android.package-archive");

        cordova.startActivityForResult((CordovaPlugin) this, intent, INSTALL_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == INSTALL_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                if (this.callbackContext != null) {                
                    this.callbackContext.success(0);
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                if (this.callbackContext != null) {                
                    this.callbackContext.success(1);
                }
            } else {
                if (this.callbackContext != null) {                
                    this.callbackContext.success("Unexpected error");
                }
            }
        }
    }
}